//
//  ParentRestListViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-9-3.
//  Copyright (c) 2014年 suplus. All rights reserved.
//
#define TextFont [UIFont systemFontOfSize:13]
#define timeFont [UIFont systemFontOfSize:12]
#define MaxReturnCount     10
#import "ParentRestListViewController.h"
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"
#import "RestListTableViewCell.h"
#import "UIAlertView+Kirinrin.h"
#import "RestApplicationViewController.h"
#import "NSDate+suplus.h"
#import "UtilHelper.h"
#import "MJRefresh.h"

@interface ParentRestListViewController ()<RestApplicationViewControllerDelegate,MJRefreshBaseViewDelegate>
@property(strong, nonatomic)NSMutableArray *tableData;
@property(weak, nonatomic)AppDelegate * appDelegate;

@property(weak,nonatomic) MJRefreshFooterView *footer;
@property(weak,nonatomic) MJRefreshHeaderView *header;
@property(nonatomic,assign)int firstReturnCount;

@end

@implementation ParentRestListViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupRefreshView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // Do any additional setup after loading the view.
    if (self.appDelegate.userType == UserTypeParent) {
        self.navigationController.title = @"托咐信息";
        
    }else{
        self.navigationController.title = @"托咐信息";
        
    }
    
//    [self loatRemoteData];
    
}
-(void)setupRefreshView
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    header.delegate = self;
    
    [header beginRefreshing];
    self.header = header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.delegate = self;
    self.footer = footer;
}
-(void)dealloc
{
    [self.header free];
    [self.footer free];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    NSString *uriString;
    if (self.appDelegate.userType == UserTypeParent) {
        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithChild.json", self.appDelegate.user[@"childId"]];
    }else{
        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithClass.json", self.appDelegate.user[@"kClassId"]];
    }

    if ([refreshView isKindOfClass:[MJRefreshFooterView class]]) {
//        上拉刷新
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"key"]= self.appDelegate.accessKey;
        parameters[@"maxReturnCount"] = [NSNumber numberWithInt:MaxReturnCount];
        parameters[@"firstReturnCount"] = [NSNumber numberWithInt:self.firstReturnCount];
        NSLog(@"key====%@",parameters);
        
        [[NetworkAccessManager shareManager] GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
            
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                NSMutableArray *temp =[NSMutableArray arrayWithArray:self.tableData];
                
                [temp[0] addObjectsFromArray:[self sortTableData:responseObject[@"data"]][0]];
                [temp[1] addObjectsFromArray:[self sortTableData:responseObject[@"data"]][1]];
               
                self.tableData = temp;
                [self.tableView reloadData];
                self.firstReturnCount += MaxReturnCount;
            }else{
                
                [UIAlertView alertWithRemoteError:resultCode];
            }
            [self.footer endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"opernation: %@\nerror: %@", operation, error);
            [UIAlertView alertWithNetworkError];
            [self.footer endRefreshing];
        }];

    }else{
//        下拉刷新
        self.firstReturnCount = 0;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"key"]= self.appDelegate.accessKey;
        parameters[@"maxReturnCount"] = [NSNumber numberWithInt:MaxReturnCount];
        parameters[@"firstReturnCount"] = [NSNumber numberWithInt:self.firstReturnCount];
        NSLog(@"key====%@",parameters);
        
        [[NetworkAccessManager shareManager] GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
            
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                self.tableData = [NSMutableArray arrayWithArray:[self sortTableData:responseObject[@"data"]]];
                [self.tableView reloadData];
                for (NSArray *dayArray in self.tableData) {
                    self.firstReturnCount +=dayArray.count;
                }
            }else{
                [UIAlertView alertWithRemoteError:resultCode];
            }
            [self.header endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"opernation: %@\nerror: %@", operation, error);
            [UIAlertView alertWithNetworkError];
            [self.header endRefreshing];
        }];

    }
}

//-(void)loatRemoteData{
//    NSString *uriString;
//    if (self.appDelegate.userType == UserTypeParent) {
//        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithChild.json", self.appDelegate.user[@"childId"]];
//    }else{
//        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithClass.json", self.appDelegate.user[@"kClassId"]];
//    }
//    
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    parameters[@"key"]= self.appDelegate.accessKey;
//    parameters[@"maxReturnCount"] = [NSNumber numberWithInt:MaxReturnCount];
//    parameters[@"firstReturnCount"] = [NSNumber numberWithInt:self.firstReturnCount];
//    NSLog(@"key====%@",parameters);
//    
//    [[NetworkAccessManager shareManagerWithCustomSetting] GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
//        
//        int resultCode = [responseObject[@"result"]intValue];
//        if (resultCode == 0) {
//            self.tableData = [self sortTableData:responseObject[@"data"]];
//            [self.tableView reloadData];
//        }else{
//            [UIAlertView alertWithRemoteError:resultCode];
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"opernation: %@\nerror: %@", operation, error);
//        [UtilHelper showAlertViewRemoteAccessFaild];
//    }];
//}

-(NSArray *)sortTableData:(NSArray *)data{
    NSMutableArray *todayArray = [NSMutableArray array];
    NSMutableArray *beforeArray = [NSMutableArray array];
    
    [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"obj %@", obj);
        RestListCellFrame *restCellFrame  = [[RestListCellFrame alloc]init];
        restCellFrame.data = obj;
        if ([UtilHelper isSameDay:[UtilHelper formatDateString:obj[@"createTime"] :nil] date2:[NSDate date]]) {
            
            //            [todayArray addObject:obj];
            [todayArray addObject:restCellFrame];
        }else{
            
            [beforeArray addObject:restCellFrame];
            //            [beforeArray addObject:obj];
        }
    }];
    return @[todayArray, beforeArray];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;    {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.tableData[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    RestListTableViewCell *cell = [RestListTableViewCell cellWithTableView:tableView];

    cell.restListCellFrame = _tableData[indexPath.section][indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    RestListCellFrame *restCellFrame = self.tableData[indexPath.section][indexPath.row];
    return restCellFrame.cellHeight;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionName;
    switch (section)
    {
        case 0:
            sectionName = @"今天";
            break;
        case 1:
            sectionName = @"之前";
            break;
            // ...
        default:
            sectionName = @"";
            break;
    }
    return sectionName;
}
- (IBAction)addRestView:(id)sender {
//    RestApplicationViewController *restAppView = [[RestApplicationViewController alloc]init];
//    restAppView.delegate =self;

//    [self performSegueWithIdentifier:@"restListToRest" sender:nil];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    id vc = segue.destinationViewController;
    NSLog(@"===%@==",vc);
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navVc =vc;
        NSArray *viewArray = [NSArray arrayWithArray:navVc.viewControllers];
        RestApplicationViewController *restAppView  =viewArray[0];
        restAppView.mm_drawerCustomerController = self.mm_drawerController;
         NSLog(@"==self.mm_drawerController=%@==",self.mm_drawerController.centerViewController);
//        restAppView.mm_drawerCustomerController.centerViewController = vc;
        restAppView.delegate =self;
    }
//    RestApplicationViewController *restAppView = [[RestApplicationViewController alloc]init];
//    restAppView.delegate =self;
    
}


#pragma mark - RestApplicationViewController的代理方法
-(void)reloadViewRestDelegate:(RestApplicationViewController *)ravc
{
    

    [self refreshViewBeginRefreshing:self.header];
    int todayCount = [NSArray arrayWithArray:self.tableData[0]].count;
    NSLog(@"self.tableData.count--%d",todayCount);
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    if(todayCount<1){
        indexPath =[NSIndexPath indexPathForRow:0 inSection:1];
    }
        
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
    
    //    [self loatRemoteData];
}
/**
 *  计算文字尺寸
 *
 *  @param text    需要计算尺寸的文字
 *  @param font    文字的字体
 *  @param maxSize 文字的最大尺寸
 */
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
@end

